package cn.wzptsoft.mall.aspect;

import cn.wzptsoft.mall.pojo.LoginUser;
import cn.wzptsoft.mall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFullAspect {

    //切入点
    @Pointcut("execution(* cn.wzptsoft.mall..*(..)) && @annotation(cn.wzptsoft.mall.aspect.AutoFull)")
    public void autoFillPointCut(){}

    //前置通知
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段填充...");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名
        AutoFull autoFull=signature.getMethod().getAnnotation(AutoFull.class);//方法注解
        OperationType operationType = autoFull.value();

        //获取当前被拦截的方法参数
        Object[] args = joinPoint.getArgs();
        if (args==null||args.length==0){
            return;
        }

        Object entity = args[0];
        //需要赋值的数据
        LocalDateTime now = LocalDateTime.now();
        //从用户信息对象中获取用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = ((LoginUser) authentication.getPrincipal()).getUser();
        //获取id
        Long id=user.getId().longValue();
        if (operationType==OperationType.INSERT){
        //为四个字段赋值
            try {
                Method createTime = entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                Method createUser = entity.getClass().getDeclaredMethod("setCreator", Long.class);
                Method updateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method updateUser = entity.getClass().getDeclaredMethod("setUpdater", Long.class);
                createTime.invoke(entity,now);
                createUser.invoke(entity,id);
                updateTime.invoke(entity,now);
                updateUser.invoke(entity,id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else if (operationType==OperationType.UPDATE){
            //为两个字段赋值
            try {
                Method updateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method updateUser = entity.getClass().getDeclaredMethod("setUpdater", Long.class);
                updateTime.invoke(entity,now);
                updateUser.invoke(entity,id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


    }

}
